﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Page</title>
    <style type="text/css">        
    </style>
    <link href="../Resource/css/ui-lightness/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" />
    <link href="../Resource/css/Paging.css" rel="stylesheet" />
    <script src="../Resource/js/jquery-1.9.1.js"></script>
    <script src="../Resource/js/jquery-ui-1.10.3.custom.js"></script>
    <script src="../Resource/js/OperCheckbox.js"></script>
</head>
<body>
    <div id="toolvar">
        <input type="button" id="btn_add" value="Add" class="btn" />
        <input type="button" id="btn_edit" value="Update" class="btn" />
        <input type="button" id="btn_del" value="Delete" class="btn" />
    </div>
    <div id="div1"></div>
</body>
</html>
<script type="text/javascript">
    var data = Array();
    for (var i = 0; i < 200; i++) {
        data.push({ Address: "Address" + i, City: "City" + String.fromCharCode(Math.floor(Math.random() * 26) + "a".charCodeAt(0)), Fax: i + 1, ID: i });
    }

    var pagingMgr = function (data, pageSize, containerid, colJson) {
        this._data = data;
        /*check data*/
        if (this._data == null || this._data == undefined) {
            return;
        }

        this._pageSize = pageSize;

        this._result = {};
        this._count = 0;
        this._controlData = null;

        this._sortTag = "";
        this._checkBoxArry = Array();
        this._containerid = containerid;
        this._dataBodycontainerid = "dataTable";
        this._pageInfocontainerid = "pagingInfo";


        this.Init = function () {
            this.GetColumns();
            this.GetResult();
            this.RenderDiv(containerid);
            this.RenderData(this._result[0]);
            this.RenderPaging($("#" + this._pageInfocontainerid));
        }

        this.ReInit = function () {
            this._result = {};
            this.GetResult();
            this.RenderData(this._result[0]);
            this.RenderPaging($("#" + this._pageInfocontainerid));
        }

        this.GetResult = function () {
            var _index = 0;

            for (var i = 0, ci; ci = this._data[i]; i++) {
                if (!this._result[_index]) {
                    this._result[_index] = [ci];
                }
                else {
                    var _len = this._result[_index].length;
                    if (_len == this._pageSize) {
                        _index++;
                        this._result[_index] = [ci]
                    }
                    else {
                        this._result[_index].push(ci);
                    }
                }
            }
            this._count = _index;
        }
        /*event*/
        this.RenderPaging = function (container) {
            if (this._data == null || this._data.length == 0) {
                return;
            }
            $(container).html("");
            var html = "";

            html += "<div style='float: left; width: 20%'><div style='float: left;' id='Records'><select id='recordsSelect' size='1'>";

            html += "<option selected='selected' value='10'>10</option>";
            html += "<option value='25'>25</option>";
            html += "<option value='50'>50</option>";
            html += "<option value='100'>100</option>";
            html += "</select>";
            html += "</div>";
            html += "<div class='recordsinfo'>Records per page</div>";
            html += "</div>";

            //html += "<div class='div_FLeft info2'>";

            if (this._data.length >= this._pageSize) {
                html += "<div class='floatright'>Records <span id='" + containerid + "_span_databegin'>" + 1 + "</span> to <span id='" + containerid + "_span_dataend'>" + this._pageSize + "</span> of " + this._data.length + "</div>";
            }
            else {
                html += "<div class='floatright'>Records <span id='" + containerid + "_span_databegin'>" + 1 + "</span> to <span id='" + containerid + "span_dataend'>" + this._data.length + "</span> of " + this._data.length + "</div>";
            }

            html += "<div class='div_FRight div_padding_right'>";

            if (this._count >= 5) {
                html += "<div class='div_FLeft div_margin_left'>";
                html += "<img src='../Resource/Image/arrove_left.png' tag='prev_img' /></div>";

                for (var i = 0; i < 5; i++) {
                    if (i == 0) {
                        html += "<div class='product_result_num1' index='" + i + "' tag='page'>" + (i + 1) + "</div>";
                    }
                    else {
                        html += "<div class='product_result_num' index='" + i + "' tag='page'>" + (i + 1) + "</div>";
                    }
                }

                html += "<div class='div_FLeft div_margin_left8'>";
                html += "<img src='../Resource/Image/arrow_right.png' tag='next_img'/></div>";
            }
            else {
                for (var i = 0; i < this._count + 1; i++) {
                    if (i == 0) {
                        html += "<div class='product_result_num1' index='" + i + "' tag='page'>" + (i + 1) + "</div>";
                    }
                    else {
                        html += "<div class='product_result_num' index='" + i + "' tag='page'>" + (i + 1) + "</div>";
                    }
                }
            }
            html += "</div>";

            $(container).append($(html));
            var that = this;
            $(container).find("img[tag=prev_img]").each(function () {
                this.addEventListener("click", function () { that.RegPrevEvent(this); }, false);
            })
            $(container).find("img[tag=next_img]").each(function () {
                this.addEventListener("click", function () { that.RegNextEvent(this); }, false);
            })
            $(container).find("div[tag=page]").each(function () {
                this.addEventListener("click", function () { that.RegPageEvent(this); }, false);
            })
            document.getElementById("recordsSelect").addEventListener("change", function () { that.RegRecordEvent(this); }, false);

            $("#recordsSelect option").each(function () {
                if ($(this).val() == that._pageSize) {
                    this.selected = true;
                }
            })

        }

        this.SetResultList = function (index) {
            $("#" + containerid + "_span_databegin").text(parseInt(index) * this._pageSize - (this._pageSize - 1));
            $("#" + containerid + "_span_dataend").text(parseInt($("#" + containerid + "_span_databegin").text()) + (this._pageSize - 1));
            if ($("#" + containerid + "_span_dataend").text() > this._data.length) {
                $("#" + containerid + "_span_dataend").text(this._data.length);
            }
        }

        this.RegPrevEvent = function (obj) {
            $(obj).parent().parent().find("div[tag=page]").each(function () {
                $(this).removeAttr("disabled");
            })

            var pageObj = $(obj).parent().parent().find("div[tag=page][class=product_result_num1]");
            var index = parseInt(pageObj.attr("index"));
            var html = parseInt(pageObj.html());
            //first page
            if (index == "0") {
                return;
            }

            pageObj.attr("class", "product_result_num");

            if (parseInt(index) % 5 == 0) {
                $(obj).parent().parent().find("div[tag=page]").each(function (j) {
                    var _h = html - 5 + j;
                    var _i = index - 5 + j;
                    if (j == 4) {
                        $(this).attr("class", "product_result_num1").html(_h).attr("index", _i);
                    }
                    else {
                        $(this).attr("class", "product_result_num").html(_h).attr("index", _i);
                    }
                })
            } else {
                pageObj.prev().attr("class", "product_result_num1");
            }


            this.RenderData(this._result[parseInt(index) - 1]);

            index = parseInt(index) - 1;
            this.SetResultList(parseInt(index) + 1);

        }

        this.RegNextEvent = function (obj) {

            $(obj).parent().parent().find("div[tag=page]").each(function () {
                $(this).removeAttr("disabled");
            })

            var pageObj = $(obj).parent().parent().find("div[tag=page][class=product_result_num1]");
            var index = parseInt(pageObj.attr("index"));
            var html = parseInt(pageObj.html());
            if (parseInt(index) == this._count) {
                return;
            }
            var that = this;

            pageObj.attr("class", "product_result_num");

            if ((parseInt(index) + 1) % 5 == 0) {
                $(obj).parent().parent().find("div[tag=page]").each(function (j) {
                    var _h = html + 1 + j;
                    var _i = index + 1 + j;
                    if (_i > that._count) {
                        $(this).attr("class", "product_result_num").html("").attr("disabled", "disabled").attr("index", "none");
                        //$(this).remove();
                    }
                    else {
                        if (j == 0) {
                            $(this).attr("class", "product_result_num1").html(_h).attr("index", _i);
                        }
                        else {
                            $(this).attr("class", "product_result_num").html(_h).attr("index", _i);
                        }
                    }
                })
            } else {
                if (pageObj.next().attr("index") == "none") {

                } else {
                    pageObj.next().attr("class", "product_result_num1");
                }
            }

            this.RenderData(this._result[parseInt(index) + 1]);

            index = parseInt(index) + 1;
            this.SetResultList(parseInt(index) + 1);
        }

        this.RegPageEvent = function (obj) {
            var obj = $(obj);
            if (obj.attr("index") != "none") {
                obj.parent().parent().parent().find("div[tag=page]").each(function () {
                    if (obj.attr("index") == $(this).attr("index")) {
                        $(this).attr("class", "product_result_num1");
                    }
                    else {
                        $(this).attr("class", "product_result_num");
                    }
                })
                var that = this;
                var _index = parseInt($(obj).attr("index"));
                that.RenderData(that._result[_index]);

                var index = obj.attr("index");
                this.SetResultList(parseInt(index) + 1);
            }
        }

        this.RegRecordEvent = function (obj) {
            this._pageSize = $(obj).val();
            this.ReInit();
        }
        /*get columns*/
        this.columnEN = new Array();

        this.GetColumns = function () {
            var _tempdata = this._data[0];
            for (var i in _tempdata) {
                this.columnEN.push(i);
            }
        }

        this.columnCN = function (colKey) {
            if (colJson == null) {
                return "";
            }
            var result = "";
            for (var i = 0; i < colJson.length; i++) {
                if (colKey == colJson[i].Key) {
                    result = colJson[i].Value;
                }
            }
            return result;
        }

        this.GetHidden = function (colName) {
            var t = null;
            for (var i = 0; i < colJson.length; i++) {
                if (colJson[i].Key == colName) {
                    t = colJson[i];
                }
            }
            return t.Hidden;
        }
        //var colData = [{ Key: 'Id', Value: '编号',Hidden:true }, { Key: 'Name', Value: '姓名',Hidden:true }, { Key: 'Age', Value: '性别',Hidden:false }];
        //var data = [{ Id: '1', Name: 'A', Age: 12 }, { Id: '1', Name: 'A', Age: 13 }];
        /*render data*/
        this.RenderData = function (data) {
            if ($("#paging_tab").length != 0) {
                $("#paging_tab").remove();
            }
            var html = "<table id='paging_tab' class='tab'>";
            /*head*/
            html += "<tr>";
            html += "<td><input type='checkbox' id='checkAll'></td>";
            for (var i = 0; i < this.columnEN.length; i++) {
                if (this.GetHidden(this.columnEN[i])) {
                    html += "<td>";
                    html += "<div class='div_FLeft itemTitle'>" + this.columnCN(this.columnEN[i]) + "</div>";
                    html += "<div class='div_FLeft'>";
                    html += "<div sortid='"+i+",0' tag='sort'> <img src='../Resource/Image/sort_arrow_up.png' /></div>";
                    html += "<div sortid='"+i+",1' tag='sort''> <img src='../Resource/Image/sort_arrow_down.png' /></div>";
                    html += "</div>";
                    html += "</td>";

                }
            }
            html += "<td>Action</td>";
            html += "</tr>";
            /*body*/
            for (var i = 0; i < data.length; i++) {
                html += "<tr tag='body'>";
                html += "<td><input type='checkbox' tag='CheckOne' pk=" + data[i][this.GetPK()] + "></td>";
                for (var j = 0; j < this.columnEN.length; j++) {
                    if (this.GetHidden(this.columnEN[j])) {
                        html += "<td>" + data[i][this.columnEN[j]] + "</td>";
                    }
                }
                html += "<td><img pk='" + data[i][this.GetPK()] + "' tag='delImg' src='../Resource/Image/close.png' /></td>";
                html += "</tr>";
            }
            html += "</table>";
            
            //$("#" + containerid).append($(html));
            $("#" + this._dataBodycontainerid).append($(html));
            
            var that = this;
            $("#" + containerid + " div[tag=sort]").each(function () {
                this.addEventListener("click", function () { that._controlData.SortData(this, that._controlData) }, false);

                var sortid2 = $(this).attr("sortid");

                if (sortid2 == that._sortTag) {
                    var sort = sortid2.split(",");
                    if (sort[1] == 0) {
                        $(this).find("img").each(function (i) {
                            $(this).attr("src", "../Resource/Image/sort_arrow_active_up.png");
                        })
                    } else {
                        $(this).find("img").each(function (i) {
                            $(this).attr("src", "../Resource/Image/sort_arrow_active_down.png");
                        })
                    }
                }
            });

            //that._checkBoxArry = null;
            $("#" + containerid + " input[type=checkbox][tag=CheckOne]").each(function () {
                that._checkBoxArry.push($(this));
            });
            that.CheckAll("checkAll", that._checkBoxArry);

            $("#"+containerid+" img[tag=delImg]").each(function () {
                this.addEventListener("click", function () { that._controlData.Delete($(this).attr("PK")); }, false);
            });
        }

        this.RenderDiv = function (container) {
            var html = "";
            html += "<div id='" + this._dataBodycontainerid + "'></div>";
            html += "<div id='" + this._pageInfocontainerid + "'></div>";
            $("#" + container).append($(html));
        }

        this.GetControlData = function (controlData) {
            this._controlData = controlData;
        }

        this.GetPK = function () {
            var pk = "";
            if (colJson == null || colJson.length == 0) {
                return;
            }
            for (var i = 0; i < colJson.length; i++) {
                if (colJson[i].PK == true) {
                    pk = colJson[i].Key;
                }
            }

            return pk;
        }

        this.GetObjById = function (id) {
            var obj = null;
            for (var i = 0; i < this._data.length; i++) {
                if (this._data[i][this.GetPK()] == id) {
                    obj = this._data[i];
                }
            }
            return obj;
        }

        this.CheckAll = function (id, checkBoxArry) {
            var _c = new ControlCheckBox($("#" + id), checkBoxArry);
            _c.CheckAll();
            _c.CheckOne();
            _c.ReCheckAll();
        }
    }

    var ControlData = function () {
        //this.data = pageObj._data;
        //this.pk = pageObj.GetPK();
        this.data = null;
        this.pk = null;
        this._pagingMgr = null;        
        this._dialogConainerId = "dialog";
        /*check data*/
        if (this.data == null || this.data == undefined) {
            //return;
        }
        this.GetPagingMgr = function (pagingMgr) {
            this._pagingMgr = pagingMgr;
            this.data = this._pagingMgr._data;
            this.pk = this._pagingMgr.GetPK();
        }
        /*insert update delete*/
        this.Insert = function () {
            var obj = new Object();
            this.CreateDialog();
            var that = this;
            $("#" + that._dialogConainerId).dialog({
                height: 300,
                width: 350,
                buttons: {
                    "Create": function () {
                        var oo = "[{";
                        $("#" + that._dialogConainerId + " input[type=text]").each(function () {
                            oo += $(this).attr("field") + ":'" + $(this).val() + "',"
                        })
                        oo = oo.substring(0, oo.length - 1) + "}]";
                        obj = eval('(' + oo + ')')[0];
                        alert(obj);
                        $("#" + that._dialogConainerId).html("");
                        $(this).dialog("close");
                    },
                    Cancel: function () {
                        $("#" + this._dialogConainerId).html("");
                        $(this).dialog("close");
                    }
                }

            });            
            //do ajax here.
        }

        this.Update = function () {

            var id = "";
            var num = 0;
            var obj = null;
            var that = this;
            $("#" + that._pagingMgr._containerid + " input[type=checkbox][tag=CheckOne]").each(function () {
                if (this.checked) {
                    id = $(this).attr("PK");
                    num++;
                }
            })
            if (num != 1) {
                alert("Error");
            } else {
                
                c.CreateDialog(id);
                $("#" + that._dialogConainerId).dialog({
                    height: 300,
                    width: 350,
                    buttons: {
                        "Save": function () {
                            var oo = "[{";
                            $("#" + that._dialogConainerId + " input[type=text]").each(function () {
                                oo += $(this).attr("field") + ":'" + $(this).val() + "',"
                            })
                            $("#" + that._dialogConainerId + " input[type=hidden]").each(function () {
                                oo += $(this).attr("field") + ":'" + $(this).val() + "',"
                            })
                            
                            oo = oo.substring(0, oo.length - 1) + "}]";
                            obj = eval('(' + oo + ')')[0];
                            
                            alert(obj);
                            $("#" + that._dialogConainerId).html("");
                            $(this).dialog("close");
                        },
                        Cancel: function () {
                            $("#" + this._dialogConainerId).html("");
                            $(this).dialog("close");
                        }
                    }

                });
            }



            //for (var i = 0; i < this.data.length; i++) {
            //    if (this.data[i][this.pk] == obj[this.pk]) {
            //        this.data[i] = obj;
            //        break;
            //    }
            //}
        }

        this.Delete = function (id) {
            var index = -1;
            for (var i = 0; i < this.data.length; i++) {
                if (this.data[i][this.pk] == id) {
                    index = i;
                    break;
                }
            }
            alert(id);
            //this.data = this.data.delByIndex(index);
        }

        this.Deletes = function () {
            var id = new Array();
            var num = 0;
            $("#" + this._pagingMgr._containerid + " input[type=checkbox][tag=CheckOne]").each(function () {
                if (this.checked) {
                    id.push($(this).attr("PK"));
                    num++;
                }
            })
            if (num == 0) {
                alert("Error");
            } else {
                alert(id);
            }
            //this.data = this.data.delByIndex(index);
        }
        /*search*/
        this.Search = function (type, str) {
            var searchArr = new Array();
            for (var i = 0; i < this.data.length; i++) {
                if (this.data[i][type].indexOf(str) != -1) {
                    searchArr.push(this.data[i]);
                }
            }

            return searchArr;
        }

        /*sort*/
        this.SortData = function (a,that) {
            var sortid = $(a).attr("sortid");
            var sort = sortid.split(",");
            var dataCopy = new Array();
            for (var i = 0; i < that._pagingMgr._data.length; i++) {
                dataCopy.push(that._pagingMgr._data[i]);
            }
            if (sort[1] == 0) {
                dataCopy = that.sortBy(that._pagingMgr.columnEN[parseInt(sort[0])], false, that.sortStringNum);
            } else {
                dataCopy = that.sortBy(that._pagingMgr.columnEN[parseInt(sort[0])], true, that.sortStringNum);
            }
            that._pagingMgr._sortTag = sortid;
            that._pagingMgr._data = dataCopy;
            that._pagingMgr.ReInit();
        }

        this.sortStringNum = function (x, y) {
            var reg = /^\d+$/g;
            var reg2 = /^\d+$/g;
            var result;
            if (reg.test(x) && reg2.test(y)) {
                var iNum1 = parseInt(x);
                var iNum2 = parseInt(y);
                if (iNum1 < iNum2) {
                    result = -1;
                } else if (iNum1 > iNum2) {
                    result = 1;
                } else {
                    result = 0;
                }
            } else {
                result = x.localeCompare(y);
                //result = x > y ? -1 : x == y ? 0 : 1;            
            }
            return result;
        }

        this.sortBy = function (prop, desc, fn) {
            arr = this.data;
            var props = [],
            ret = [],
            i = 0,
            len = arr.length;
            if (typeof prop == 'string') {
                for (; i < len; i++) {
                    var oI = arr[i];
                    (props[i] = new String(oI && oI[prop] || ''))._obj = oI;
                }
            }
            else {
                throw '参数类型错误';
            }

            if (fn != null && typeof fn == 'function') {
                props.sort(fn);
            } else {
                props.sort();
            }
            for (i = 0; i < len; i++) {
                ret[i] = props[i]._obj;
            }
            if (desc) ret.reverse();
            return ret;
        }

        /*dialog*/
        this.CreateDialog = function (id) {

            $("#paging_div_dialog").remove();
            if (!document.getElementById(this._dialogConainerId)) {
                var newDiv = document.createElement("div");
                newDiv.id = this._dialogConainerId;
                newDiv.style.display = "none";
                document.body.appendChild(newDiv);
            }
            $("#" + this._dialogConainerId).html("");
            var html = "";
            html += "<table class='tab'>";
            if (id == "" || id == null) {
                for (var j = 0; j < this._pagingMgr.columnEN.length; j++) {
                    if (this._pagingMgr.GetHidden(this._pagingMgr.columnEN[j])) {
                        html += '<tr>';
                        html += "<td>" + this._pagingMgr.columnCN(this._pagingMgr.columnEN[j]) + ":</td>";
                        html += "<td><input type='text' field='" + this._pagingMgr.columnEN[j] + "' /></td>";
                        html += "</tr>";
                    }
                }
            } else {
                var obj = this._pagingMgr.GetObjById(id);
                html += "<input type='hidden' field='" + this._pagingMgr.GetPK() + "' value='" + obj[this._pagingMgr.GetPK()] + "'>";
                for (var j = 0; j < this._pagingMgr.columnEN.length; j++) {
                    if (this._pagingMgr.GetHidden(this._pagingMgr.columnEN[j])) {
                        html += '<tr>';
                        html += "<td>" + this._pagingMgr.columnCN(this._pagingMgr.columnEN[j]) + ":</td>";
                        html += "<td><input type='text' field='" + this._pagingMgr.columnEN[j] + "' value='" + obj[this._pagingMgr.columnEN[j]] + "'/>";
                        html += "</td>";
                        html += "</tr>";
                    }
                }
            }
            html += '</table>';
            $("#" + this._dialogConainerId).append($(html));

        }

        /*init*/
        this.Init = function (o) {

        }

        Array.prototype.delByIndex = function (index) {
            if (index < 0) {
                return this;
            }
            else {
                return this.slice(0, index).concat(this.slice(index + 1, this.length));
            }
        }
        String.prototype.IsNumber = function () {
            var reg = /^\d+$/g;
            return reg.test(this);
        }
    }

    var colData = [{ Key: 'Address', Value: '地址', Hidden: true, PK: false }, { Key: 'City', Value: '城市', Hidden: true, PK: false },
        { Key: 'Fax', Value: '传真', Hidden: true, PK: false }, { Key: 'ID', Value: '主键', Hidden: false, PK: true }]
    
    var c = new ControlData();
    var s = new pagingMgr(data, 10, "div1",colData);
    s.GetControlData(c);
    s.Init();
    c.GetPagingMgr(s);

    $("#btn_add").click(function () {
        var obj = null;        
        c.Insert();
    })

    $("#btn_edit").click(function () {
        c.Update();
    })

    $("#btn_del").click(function () {
        c.Deletes();
    })
</script>
